<?php 
class PostController extends ApiController {
	
	public function actionSearch() {
		$t = new Post('search');
		$t->attributes = $_GET;
		$models = $t->searchApi();
		$result = array();
		
		foreach($models as $model) {
			$data = $model->attributes;
			$data['user'] = $model->user->getPublicInfo();
			$result[] = $data;
		}
		$this->_sendSuccess($result);
	}
	
	public function actionCreate() {
		$model = new Post();
		$model->attributes = $_POST;
		$model->created_time = date('Y-m-d H:i:s');
		if (!$model->save()) {
			$this->_sendError($model->getErrors(), 400);
		}
		
		// decrease point
		$author = $model->user;
		$author->addPoint('write_bulletin', false);
		
		$result = $model->id;
		$this->_sendSuccess($result);
	}
	
	public function actionUpdate($id) {
		$model = Post::model()->findByPk($id);
		if (!$model) {
			$this->_sendError('Post not exists', 400);
		}
		
		$model->attributes = $_POST;
		if (!$model->save()) {
			$this->_sendError($model->getErrors(), 400);
		}
			
		$this->_sendSuccess(1);
	}
}